<template>
  <el-button
    type="primary"
    plain
    icon="Plus"
    @click="handleAdd"
    >新增</el-button
  >
  <el-button type="success" plain icon="Check" @click="handleCopy"
    >复制上月</el-button
  >
  <el-button color="#626aef" :dark="isDark" plain icon="Upload" @click="handleUP"
    >导入</el-button
  >
  <el-tooltip class="item" effect="dark" content="刷新" placement="top">
    <el-button circle icon="Refresh" @click="update" />
  </el-tooltip>
  <div class="opinion">
      <div style="width:100%;color: #00A8E8;margin-bottom:8px;"><el-icon><ChatLineSquare/></el-icon>Tip</div>
      <div>模版一：
        <span style="color:#00A8E8">提成条目一</span>
      <span style="color:#FFB400;font-size:22px;">&nbsp;&nbsp;&gt;</span>
      （<span style="color:#00A8E8">条目二的百分比</span>
      <span style="color:#FFB400;font-size:22px;">&nbsp;×&nbsp;</span>
      <span style="color:#00A8E8">提成条目二</span>），则获得（
      <span style="color:#00A8E8">结算百分比</span>
      <span style="color:#FFB400;font-size:22px;">&nbsp;×&nbsp;</span>
      <span style="color:#00A8E8">提成条目二</span>）
      </div>
      <div>
        模版二：
        <span style="color:#00A8E8">结算</span>
        <span style="color:#FFB400;font-size:22px;">&nbsp;=&nbsp;</span>
      <span>（</span>
      <span style="color:#00A8E8">提成条目一</span>
      <span style="color:#FFB400;font-size:22px;">&nbsp;&nbsp;-&nbsp;&nbsp;</span>
      <span style="color:#00A8E8">提成条目二</span>
      <span>）</span>
      <span style="color:#FFB400;font-size:22px;">&nbsp;×&nbsp;</span>
      <span style="color:#00A8E8">结算百分比</span>
      </div>
      </div>
  <!--<el-button color="#626aef" :dark="isDark" plain icon="Upload" @click="handleUP"
    >导入</el-button
  >-->
  
  <el-table
    :data="KpiRuleList"
    border
    style="width: 95%; margin: 20px 0px; border-radius: 8px;box-shadow: 5px 5px 10px rgba(64, 158, 255, 0.5);"
    :header-cell-style="{
      background: '#337ecc !important',
      color: '#ffffff',
      border: 'none !important',
      textAlign: 'center',
    }"
    :span-method="(value) => rowSpanRulesHandler(value, KpiRuleList)"
  >
    <el-table-column prop="name" label="KPI指标" width="200"></el-table-column>
    <el-table-column
      prop="target1,target2,rulePercent"
      label="规则"
      width="150"
      class-name="my-content"
    >
      <template #default="scope">
        <div v-show="scope.row.type==1">
          {{ scope.row.target1 }}&gt;{{ scope.row.target2
        }}{{ scope.row.rulePercent }}%
        </div>
        <div v-show="scope.row.type==2">
          {{ scope.row.target1 }}-{{ scope.row.target2}}
        </div>
      </template>
    </el-table-column>
    <el-table-column
      prop="target2,resultPercent"
      label="提成"
      width="150"
      class-name="my-content"
    >
      <template #default="scope">
        <div v-show="scope.row.type==1">
          <el-tag disable-transitions>{{ scope.row.resultPercent }}%</el-tag>
          {{ scope.row.target2 }}
        </div>
        <div v-show="scope.row.type==2">
          <el-tag disable-transitions>{{ scope.row.resultPercent }}%</el-tag>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      prop="state"
      label="状态"
      width="82"
      align="center"
    >
      <template #default="scope">
        <el-tag
          :type="scope.row.state === 0 ?'danger' : 'success'"
          disable-transitions
          >{{ scope.row.state === 0 ? "未启用" : "启用" }}</el-tag
        >
      </template>
    </el-table-column>
    <el-table-column label="最后更新时间" width="210">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <el-icon><timer /></el-icon>
          <span style="margin-left: 10px">{{ scope.row.updateTime }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="ins" label="备注"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)" 
          >编辑</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <pagination
    class="pagination"
    v-show="KpiListPage.total > 0"
    :total="KpiListPage.total"
    v-model:page="PageForm.page"
    v-model:limit="KpiListPage.size"
    @pagination="handlePagination"
  />
  <Dialog
    v-model="dialogFormVisible"
    :CadreList="CadreList"
    :close="close"
    :update="update"
    :selectContent="selectContent"
    :type="type"
    :title="title"
  ></Dialog>
  <FormDialog
    v-model="dialog"
    :close="closeForm"
    :update="update"
  ></FormDialog>
  <UploadExcel
        v-model="upload.open"
        :title="upload.upLoadTitle"
        :url="importUrl"
        :tipShow="true"
        @onSuccess="onSuccess"
        @onDownTemplate="onDownTemplate"
      ></UploadExcel>
</template>
<script setup>
import {
  ref,
  onMounted,
  onBeforeMount,
  reactive,
  defineEmits,
  watch,
} from "vue";
import { getRulePage, deletetRule, updatetRule,copy } from "@/api/kpi";
import Dialog from "./KpiDialog";
import FormDialog from "./kpiForm";
import { ElMessage } from "element-plus";
import {getKpiTemplate} from "@/api/template";
import UploadExcel from "@/components/SendAndDownload/index";

const PageForm = ref({
  page: 1,
  page_size: 10,
});
const KpiListPage = ref([]);
const KpiRuleList = ref([]);
onBeforeMount(() => {
  getRulePage(PageForm.value).then((data) => {
    KpiListPage.value = data.data;
    KpiRuleList.value = data.data.records;
  });
});
watch(
  KpiRuleList,
  (newVal) => {
    
  },
  { deep: true }
);

const handlePagination=(value)=>{
    getRulePage(value).then(data=>{
        KpiListPage.value = data.data;
        KpiRuleList.value = data.data.records;
    })
}

const importUrl = ref('/KpiRule/upload');
const upload = ref({
  open: false,
  upLoadTitle: "提成考核条目上传",
});
const onSuccess = (res) => {
    getRulePage(value).then(data=>{
        KpiListPage.value = data.data;
        KpiRuleList.value = data.data.records;
    })
  upload.value.open = false;
};
const handleUP = () => {
  upload.value.open = true;
};
const onDownTemplate = () => {
  getKpiTemplate()
};

const title = ref("新增提成条目");
const type = ref("add");
const selectContent = ref([]);
const dialogFormVisible = ref(false);
const handleAdd = () => {
  selectContent.value = {
    id: "",
    name: "",
    target1: "",
    target2: "",
    type:"",
    state: "",
    ins: "",
  };
  title.value = "新增提成条目";
  type.value = "add";
  dialogFormVisible.value = true;
};
const handleEdit = (index, row) => {
  selectContent.value = {
    id: "",
    name: "",
    target1: "",
    target2: "",
    state: true,
    ins: "",
  };
  selectContent.value = row;
  title.value = "编辑提成条目";
  type.value = "edit";
  dialogFormVisible.value = true;
};
const handleDelete = (index, row) => {
  deletetRule(row).then((data) => {
    if (data.code == 200) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      update();
    } else {
      ElMessage.error("删除失败");
    }
  });
};

const dialog = ref(false);
const handleCopy=()=>{
  dialog.value = true;
}
const closeForm = () => {
  dialog.value = false;
};

const close = () => {
  dialogFormVisible.value = false;
};
const update = (form) => {
  getRulePage(PageForm.value).then((data) => {
    if (data.code == 200) {
      ElMessage({
        message: "更新成功",
        type: "success",
      });
      KpiListPage.value = data.data;
      KpiRuleList.value = data.data.records;
    } else {
      ElMessage.error("更新失败");
    }
  });
};

const compareSingleAttrReturnColSpan = (row, compareAttr, index, tableData) => {
  let count = 0;
  let start = index;
  let multCompare = true;

  while (start < tableData.length && multCompare) {
    start++;
    count++;
    //multCompare = row[compareAttr] === tableData[start]?.[compareAttr];//依旧符合相等条件
    //console.log(row.empId,tableData[start].empId);
    if (start <= tableData.length - 1)
      multCompare = row.id === tableData[start].id;
    else multCompare = row.id === tableData[start - 1].id;
  }
  start--; //退出循环后的 新起始行 index

  if (start < tableData.length) {
    tableData[index][`${compareAttr}_count`] = count; //将合并的行数存储在行数据中的一个特定属性中
  }

  if (index > 0 && count + 1 === tableData[index - 1][`${compareAttr}_count`]) {
    return [0, 0]; //不需要合并
  }
  return [count, 1];
};

const columns = [
  "name",
  "target1",
  "target2",
  "state",
  "updateTime",
  "ins",
  "operate",
];
const rowSpanRulesHandler = ({ row, column, rowIndex, columnIndex }, data) => {
  if (
    columns[columnIndex] === "name" ||
    columns[columnIndex] === "ins" ||
    columns[columnIndex] === "operate"
  ) {
    const r = compareSingleAttrReturnColSpan(row, "emp_id", rowIndex, data);
    return r;
  }
};
</script>

<style lang="scss" scoped>
.title1 {
  color: rgb(64, 158, 255);
  width: 300px;
  height: 45px;
  font-size: 25px;
  background: rgba(64, 158, 255, 0.4);
  text-align: center;
  border-radius: 10px;
  margin: 10px auto 10px;
  line-height: 45px;
  border-top: #409eff 2px solid;
  border-bottom: #409eff 2px solid;
  box-shadow: 5px 5px 10px rgba(64, 158, 255, 0.5);
}
.pagination {
  margin: 20px 50px;
  display: flex;
  justify-content: end;
}
.el-table__body td {
     border: 2px solid black; /* 自定义表格内线条颜色 */
}
.opinion {
  width: 800px;
  height: 100%;
  border-radius: 8px;
  color: #363636;
  display: inline-block;
  border: #FFB400 2px dashed;
  background: #fff;
  margin: 10px 20px;
  padding: 10px;
}
</style>